package twb.controller;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import twb.entity.Customer;
import twb.util.EMF;

@Controller
public class CustomerController {

	@RequestMapping(value="/create/{name}",method=RequestMethod.GET)
	public String hello(@PathVariable String name, Model model) {		
		EntityManager entityManager = new EMF().entityManager();
		EntityTransaction trx = entityManager.getTransaction();
        Customer newCustomer = new Customer();
        newCustomer.setFirstName(name + System.currentTimeMillis());
        newCustomer.setLastName(name + System.currentTimeMillis());
        model.addAttribute("newCustomer", newCustomer);
        trx.begin();
        entityManager.persist(newCustomer);        
        entityManager.flush();
        trx.commit();
		return "/hello";
	}
	
	@RequestMapping("/display")
	public String display(Model model) {
		EntityManager entityManager = new EMF().entityManager();		                     
        Customer c = entityManager.find(Customer.class, 1);
        Query query = entityManager.createQuery("select c from Customer c");
        List<Customer> list = query.getResultList();
        model.addAttribute("customers", list );
		return "/displayCustomer";
	}
/*	@RequestMapping("{name}")
    public ModelAndView createCustomer() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("Customer");
        mav.addObject("message", "Hello World!");
        return mav;
    }
*/
}
